package com.imut.lagain.controller;

import com.imut.lagain.service.IWeChatService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


import java.io.IOException;
import java.util.Map;

/**
 * 微信服务控制器
 */

@RestController
@RequestMapping("/api/wechat")
public class WechatServiceController {
    private static final Logger log = LoggerFactory.getLogger(WechatServiceController.class);

    @Autowired
    private IWeChatService wechatService;

    /**
     * 微信服务器验证
     */
    @GetMapping("/verify")
    public String verifyWechatServer(@RequestParam String signature,
                                   @RequestParam String timestamp,
                                   @RequestParam String nonce,
                                   @RequestParam String echostr) {
        log.info("微信服务器验证请求: signature={}, timestamp={}, nonce={}", signature, timestamp, nonce);
        
        if (wechatService.verifySignature(signature, timestamp, nonce)) {
            log.info("微信服务器验证成功");
            return echostr;
        } else {
            log.warn("微信服务器验证失败");
            return "验证失败";
        }
    }

    /**
     * 处理微信消息
     */
    @PostMapping("/message")
    public void handleWechatMessage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.info("收到微信消息");
        wechatService.handleMessage(request, response);
    }

    /**
     * 获取微信访问令牌
     */
    @GetMapping("/access-token")
    public ResponseEntity<Map<String, Object>> getAccessToken() {
        log.info("获取微信访问令牌");
        Map<String, Object> result = wechatService.getAccessToken();
        return ResponseEntity.ok(result);
    }

    /**
     * 发送模板消息
     */
    @PostMapping("/template-message")
    public ResponseEntity<Map<String, Object>> sendTemplateMessage(@RequestBody Map<String, Object> request) {
        log.info("发送微信模板消息: {}", request);
        Map<String, Object> result = wechatService.sendTemplateMessage(request);
        return ResponseEntity.ok(result);
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/user-info")
    public ResponseEntity<Map<String, Object>> getUserInfo(@RequestParam String openid) {
        log.info("获取微信用户信息: openid={}", openid);
        Map<String, Object> result = wechatService.getUserInfo(openid);
        return ResponseEntity.ok(result);
    }
}